package com.wenheng.service.impl;

import com.wenheng.Mapper.SeckillMapper;
import com.wenheng.Mapper.SeckillproductMapper;
import com.wenheng.client.OrderClient;
import com.wenheng.service.SeckillingService;
import com.wenheng.vo.entity.Seckillproduct;
import com.wenheng.vo.entity.SeckillproductExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: 文恒
 * @Date: 2021/3/25 - 03 - 25 -17:01
 * @Description:com.wenheng.service.impl
 * @version:1.0
 */
@Service
@Transactional
public class SeckillingServiceImpl implements SeckillingService {
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    public SeckillproductMapper seckillproductMapper;
    @Autowired
    public OrderClient orderClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //判断库存
    @Override
    public Seckillproduct CommoditiesAndActivities(Integer id, Integer activityId) {
        if(seckillMapper.selectByPrimaryKey(activityId)!=null){
            SeckillproductExample example = new SeckillproductExample ();
            SeckillproductExample.Criteria criteria = example.createCriteria();
            criteria.andSeckillidEqualTo(activityId).andProdectidEqualTo(id);
            List<Seckillproduct> list = seckillproductMapper.selectByExample(example);
            for (Seckillproduct seckillproduct : list) {
                if (!seckillproduct.getLimitquantity().equals(seckillproduct.getSold())){
                    return seckillproduct;
                }
            }
        }
        return null;
    }

    //更改库存  同时生成订单  二者同时进行  方法最上面 进行开启事务
    @Override
    public int ExecutiveBusiness(Seckillproduct seckillproduct,String token){
        //更改库存
        int i  = seckillproductMapper.updateSeckill(seckillproduct);
        //生成订单
        if(i>0) {
            String code = orderClient.createOrder(11, seckillproduct.getProdectid(), seckillproduct.getSold(),token);
            if(redisTemplate.hasKey(code)){
                if(redisTemplate.opsForValue().get(code).equals("1")){
                    //完成全部工作
                    redisTemplate.delete(code);  //移除分布式锁
                }else{
                    throw new RuntimeException("订单生成异常");
                }
            }else{
                throw new RuntimeException("订单生成异常");
            }
        }
        //订单发生意料之外的情况   需要回滚所有事务
        return 200;
    }

}
